# -*- coding: utf-8 -*-
import webtool
import model

uimode = False

def setUIMode(isui):
    global uimode
    uimode = isui

def match( post, matchconfig, lasttime, notifyfunc ):
    if not postAfterTime(post, lasttime):
        return
    matched = False
    if matchconfig.watchargs.newPostMode:
        matched = True
    if not matched:
        matched =  matchStr(post, post.getTitle(), matchconfig.watchargs) 
    if not matched and matchconfig.watchargs.contentMatch:
        if not post.getContent():
            matchconfig.adapter.getPostDetail(post)
        matched = matchStr(post, post.getContent(), matchconfig.watchargs)
    if matched:
        if not post.getContent():
            matchconfig.adapter.getPostDetail(post)
        result = model.MatchResult(post, matchconfig)
        notify(result, notifyfunc)
        
    
def matchStr(post, str, matchargs):
    func = None
    
    if model.WatchArgs.MATCH_TYPE_AND == matchargs.matchType:
        func = matchAnd
    elif model.WatchArgs.MATCH_TYPE_OR == matchargs.matchType:
        func = matchOr
    return func(processStrCase(str,matchargs), processKeywordsCase(matchargs.keywords, matchargs))

def processKeywordsCase(keywords, matchargs):
    return [processStrCase(k, matchargs) for k in keywords]

def processStrCase(str, matchargs):
    if matchargs.ignoreCase:
        return str.upper()
    else:
        return str

def matchOr(str, keywords):
    if not len(keywords) or not str:
        return False
    for keyword in keywords:
        if keyword in str:
            return True
    return False

def matchAnd(str, keywords):
    if not len(keywords) or not str:
        return False
    for keyword in keywords:
        if keyword not in str:
            return False
    return True

def postAfterTime(post, time):
    if not time:
        return True
    elif not post.getTime():
        return False
    else:
        return post.getTime() > time
        
def latestTime(postlist):
    time = None
    for p in postlist:
        if p.getTime():
            if not time or p.getTime()>time:
                time= p.getTime()
    return time

def notify(matchresult, notifyfunc = None):
    post = matchresult.post
    msg = u'\n'.join((
                     u'帖子标题: %s' %(post.getTitle(),),
                     u'发贴时间: %s' %(time.asctime(post.getTime()),),
                     u'发帖用户: %s' %(post.getUser(),),
                     u'帖子链接：%s' %(post.getLink(),),
                     u'内    容: \n%s' %(post.getContent(),)
                     ))
    if uimode and notifyfunc:
        notifyfunc(msg, matchresult)
    else:
        printmsg(msg)
        

def printmsg(msg):
    if not uimode:
        print msg


import threading
import time
class BBSWatcher(threading.Thread):
    def __init__(self, config, timespan, notifyfunc = None):
        threading.Thread.__init__(self)
        self.config = config
        self.lastTime = None
        self.stopped = False
        self.timespan = timespan
        self.notifyfunc = notifyfunc
        self.timeToQuit = threading.Event()
        self.timeToQuit.clear()
        
    def run(self):
        self.stopped = False
        while not self.timeToQuit.isSet():
            lastTime = self.drive(self.config, self.lastTime, self.notifyfunc)
            
            if lastTime:
                self.lastTime = lastTime
            if self.timeToQuit.isSet():
                break
            self.timeToQuit.wait(self.timespan)
            
    def stop(self):
        self.timeToQuit.set()
        
    def drive(self, matchconfig, lasttime,notifyfunc = None):
        lst = matchconfig.adapter.getPostList(matchconfig.watchargs.themeMode)
        for p in lst:
            if self.timeToQuit.isSet():
                break
            match( p, matchconfig, lasttime, notifyfunc)
        return latestTime(lst)

if __name__ == '__main__':
    from adapter.smth import ConcreteAdapter
    adapter = ConcreteAdapter()
    adapter.setBoardName('SecondMarket')
    args = model.WatchArgs()
    args.setKeywords([u'hz'])
    args.enableContentMatch(True)
    args.setMatchType(model.WatchArgs.MATCH_TYPE_OR)
    args.enableNewPostMode(True)
    w = BBSWatcher(model.WatchConfig(u'name',adapter, args),10)
    w.start()
    
